<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsClassify;
use App\Models\GoodsSku;
use App\Models\Sharp;
use App\Models\SharpToGoods;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SharpGoodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Content $content)
    {
		$default = SharpToGoods::with(['goods:id', 'goods.classify:id,title'])
			->where('sharp_id', $id)
			->whereNull('goods_sku_id')
			->get();
		
    	$goodsClassify = GoodsClassify::where('store_id', Admin::user()->store_id)->get(['id', 'title']);
    	
    	$goods = Goods::whereIn('id', array_keys($default->pluck('goods_id', 'goods_id')->toArray()))
		    ->withTrashed()->get(['id', 'name']);
    	
	    $goodsSku = [];
	    $default->map(function ($item) use (&$goodsSku) {
	    	foreach ($item->goods->goodsSku as $k => $v) {
	    	    if ($item->goods_sku_id == $v->id) {
	    	    	$goodsSku[$item->goods_id] = [
	    	    		$v->id => $v->attribute_string
			        ];
		        }
		    }
	    });
	    
	    $goodsClassify = $goodsClassify->pluck('title', 'id');

	    return $content->header('添加秒杀商品')
		        ->row(view('admin.sharps.box-header', ['title' => '无属性规格']))
		        ->body(view('admin.sharps.sharp-edit-noSku', compact('id', 'default', 'goodsClassify', 'goods', 'goodsSku')));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $param = $request->only(['id', 'numbers', 'materials', 'price', 'linePrice']);
        $validate = Validator::make($param, [
            'id' => 'required',
		    'numbers' => 'required',
		    'materials' => 'required',
		    'price' => 'required',
		    'linePrice' => 'required'
        ]);
        if ($validate->fails()) {
        	return json(400, 1, $validate->errors()->first(), $param);
        }
        $data = [];
		for ($i = 0; $i < count($param['price']); $i++) {
			$data[] = [
				'sharp_id' => $id,
				'goods_id' => $param['materials'][$i]['material_id'],
				'goods_sku_id' => null,
				'stock' => $param['numbers'][$i]['number'],
				'price' => (int)$param['price'][$i]['price'] * 100,
				'line_price' => (int)$param['linePrice'][$i]['linePrice'] * 100,
				'created_at' => Carbon::now(),
				'updated_at' => Carbon::now()
			];
		}
		//活动开始前可以修改
	    $goods = SharpToGoods::where('sharp_id', $id)->get()->toArray();
		$sharp = Sharp::find($id);
		if (!empty($goods) && $sharp->active_start < Carbon::now()) {
			return json(400, 1, '活动已经开始，不方便再修改');
		}
		$res = true;
		//返回无属性规格商品库存
	    
	    SharpToGoods::prepareReturnStockWithoutSku($id);
		//减少sku库存
	    if (!empty($data['goods_sku_id'])) {
	        $res = SharpToGoods::prepareReduceStockWithoutSku(collect($data)->pluck('stock', 'goods_id')->toArray());
	    }
	    
		if ($res !== true) {
			return json(400, 1, $res, $data);
		}
	    // 删除关联
	    SharpToGoods::where('sharp_id', $id)->forceDelete();
        $res = DB::table('sharp_to_goods')->insert($data);
        
        if ($res) {
        	return response([
        		'status' => 201,
		        'code' => 1,
		        'msg' => '创建成功',
		        'data' => $data
	        ]);
        } else {
        	return response([
        		'status' => 500,
		        'code' => 1,
		        'msg' => '创建失败',
		        'data' => $data
	        ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    
    public function getGoods(Request $request)
    {
	    $param = $request->all();
        $validate = Validator::make($request->all(), [
        	'goods_classify_id' => 'required',
        ]);
        if($validate->fails()){
        	return response(['code' => 1, 'msg' => $validate->errors()->first()]);
        }
        $goods = GoodsClassify::with(['goods' => function ($q) use ($param) {
            $q->whereNotIn('goods_id', $param['material_id'])->selectRaw('goods_id as id,name');
        }])->find($param['goods_classify_id']);
        //dd($goods->toArray());
	    //dd($goods->pluck('goods_id'));
	    
        $data = [];
        foreach ($goods->goods as $k => $v) {
            $data[] = $v;
        }
        if (Arr::get($param, 'no_sku', 0)) {
	       $sku = GoodsSku::whereIn('goods_id', $goods->goods->pluck('id'))->get()->pluck('goods_id', 'goods_id')->toArray();

	       // dd($sku->pluck('goods_id', 'goods_id')->toArray());
	       static $temp =[];
	       foreach ($data as $k => $item) {
				if (!Arr::get($sku , $item->id, 0)) {
					$temp[] = $item;
				}
	       }
	       $data = $temp;
	    }
        return response([
        	'code' => 1,
	        'msg' => '查询成功',
	        'data' => $data
        ]);
    }
    
    public function OgetGoods(Request $request)
    {
	    $param = $request->all();
        $validate = Validator::make($request->all(), [
        	'goods_classify_id' => 'required',
        ]);
        if($validate->fails()){
        	return response(['code' => 1, 'msg' => $validate->errors()->first()]);
        }
        $goods = GoodsClassify::with(['goods' => function ($q) use ($param) {
            $q->whereNotIn('goods_id', $param['material_id'])->selectRaw('goods_id as id,name');
        }])->find($param['goods_classify_id']);
        //dd($goods->toArray());
	    GoodsSku::whereIn('goods_id', $goods->pluck('goods_id'))->get();
        $data = [];
        foreach ($goods->goods as $k => $v) {
            $data[] = $v;
        }
        return response([
        	'code' => 1,
	        'msg' => '查询成功',
	        'data' => $data
        ]);
    }
}
